//
//  DLNetWorkManager.m
//  delongzhitou
//
//  Created by Mr.Wang on 2018/11/22.
//  Copyright © 2018 delongzhitou. All rights reserved.
//

#import "DLNetWorkManager.h"
#import "DLNetWorkDefine.h"


@implementation DLNetWorkManager

static DLNetWorkManager *_manager;

+ (instancetype)shareInstance {
    
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _manager = [self manager];
        
        _manager.requestSerializer  = [AFHTTPRequestSerializer serializer];
        _manager.responseSerializer = [AFJSONResponseSerializer serializer];
        _manager.securityPolicy     = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModeNone];
        _manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:
                                                              @"application/json",
                                                              @"text/html",
                                                              @"text/plain",
                                                              @"text/javascript",
                                                              @"text/xml",
                                                              @"image/*",
                                                              @"text/json",nil];;
    });
    return _manager;
}


/**
 @param parameters body中的参数
 */
- (void)setHTTPHeaderWithBodyParameters:(NSDictionary *)parameters {
    
    NSString *uniqueId = [DLKeyChainManager readUUID];
    if (isEmpty(uniqueId)) {
        uniqueId = [DLKeyChainManager createUUID];
        [DLKeyChainManager saveUUID:uniqueId];
    }
    [self.requestSerializer setValue:uniqueId forHTTPHeaderField:@"devicecode"];
    [self.requestSerializer setValue:kuserManager.isLogin?kuserManager.userInfoModel.token:@"" forHTTPHeaderField:@"token"];
    [self.requestSerializer setValue:@"ios" forHTTPHeaderField:@"platform"];
    
    NSString *version = ([[NSBundle mainBundle] infoDictionary][@"CFBundleShortVersionString"]);
    [self.requestSerializer setValue:version forHTTPHeaderField:@"version"];
}

#pragma mark - PublicMethods
- (NSURLSessionDataTask *)requestWithMethod:(DLRequestMethod)method path:(NSString *)path parameters:(NSDictionary *)parameters success:(void (^)(id responseObject))responseSuccess failure:(void (^)(NSError *error))responseFailure {
    
    if (isEmpty(path)) {
        NSAssert(path, @"request path can`t be nil");
        return nil;
    }
    _manager.requestSerializer = [AFHTTPRequestSerializer serializer];
    
    NSString *requestUrl = [kAPIBaseString stringByAppendingString:path];
    
    NSLog(@"请求的参数是：%@", parameters);
    
    [self setHTTPHeaderWithBodyParameters:parameters];
    if (DLRequestMethodGET == method) {
        return [self GETRequestWithPath:requestUrl parameters:parameters success:responseSuccess failure:responseFailure];
    } else if (DLRequestMethodPOST == method) {
        return [self POSTRequestWithPath:requestUrl parameters:parameters success:responseSuccess failure:responseFailure];
    }
    return nil;
}

#pragma mark - PrivateMethods
- (NSURLSessionDataTask *)GETRequestWithPath:(NSString *)path parameters:(NSDictionary *)parameters success:(void (^)(id responseObject))responseSuccess failure:(void (^)(NSError *error))responseFailure {
    NSLog(@"GET请求的链接是：%@", path);
    NSURLSessionDataTask *task = [self GET:path parameters:parameters progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
//        if (![path containsString:HTTPInformationList]) {
            //base64太长了 没法看log
            NSLog(@"GET请求成功，返回的参数是:%@", responseObject);
//        }
        
        if ([[responseObject objectForKey:@"code"] intValue]==-1) {
            NSLog(@"强制更新");
            [self mustUpdateApp:responseObject];
            return;
        }
        
        
        if (responseSuccess) {
            responseSuccess(responseObject);
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"GET请求失败，返回的参数是:%@", error);
        if (responseFailure) {
            responseFailure(error);
        }
    }];
    return task;
}

- (NSURLSessionDataTask *)POSTRequestWithPath:(NSString *)path parameters:(NSDictionary *)parameters success:(void (^)(id responseObject))responseSuccess failure:(void (^)(NSError *error))responseFailure {
    
    NSLog(@"POST请求的链接是：%@", path);
    NSURLSessionDataTask *task = [self POST:path parameters:parameters progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
//        if (![path containsString:HTTPInformationList]) {
            //base64太长了 没法看log
            NSLog(@"POST请求成功，返回的参数是:%@", responseObject);
//        }
        
        if ([[responseObject objectForKey:@"code"] intValue]==-1) {
            NSLog(@"强制更新");
            [self mustUpdateApp:responseObject];
            return;
        }
        if (responseSuccess) {
            responseSuccess(responseObject);
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"POST请求失败，返回的参数是:%@", error);
        if (responseFailure) {
            responseFailure(error);
        }
    }];
    return task;
}
- (void) mustUpdateApp:(NSDictionary *)responseObject {
    
    [[NSNotificationCenter defaultCenter] postNotificationName:@"HTTPMustUpdateAppVersion" object:nil];
    
    NSString *content = [NSString stringWithFormat:@"%@", responseObject[@"message"]];
    
    //弹出提示框
    UIAlertController *upDateAlert = [UIAlertController alertControllerWithTitle:@"发现新版本" message:kSafeString(content) preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *updateAction = [UIAlertAction actionWithTitle:@"更新" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {
        [self updateNewVersion];
    }];
    
    UIAlertAction *doNotUpdateAction = [UIAlertAction actionWithTitle:@"退出" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        exit(0);
    }];
    
    [upDateAlert addAction:doNotUpdateAction];
    [upDateAlert addAction:updateAction];
    [kuserManager.lastVc presentViewController:upDateAlert animated:YES completion:^{
        
        
    }];
}
- (void) updateNewVersion {
    
    NSString *postUrl = HTTPCheckAppUpdateInfo;
    NSDictionary *postDic = @{};
    [[DLNetWorkManager shareInstance] requestWithMethod:DLRequestMethodPOST path:postUrl parameters:postDic success:^(id  _Nonnull responseObject) {
        
        if (kRequestSuccess(responseObject)) {
            NSDictionary *resultDic = responseObject[@"result"];
            NSString *downloadPageUrl = [NSString stringWithFormat:@"%@", resultDic[@"downloadPageUrl"]];
            
            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:downloadPageUrl] options:@{} completionHandler:^(BOOL success) {
                
            }];
        }
    } failure:^(NSError * _Nonnull error) {
        NSLog(@"请求接口失败，错误是：%@", error);
    }];
    
    
    
    
}

@end
